using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using LP;
using System.Threading;
using System;
using UnityEditor;
using UnityEngine.UIElements;

public sealed class TimeMgr : AbsMgr
{
    private IDGenerator timerIdGenerator = new IDGenerator();
    private Dictionary<int, Coroutine> timerCoroutines = new Dictionary<int, Coroutine>();

    /// <summary>
    /// 启动计时器
    /// </summary>
    /// <param name="cancellationToken"></param>
    /// <param name="callBack">计时器事件</param>
    /// <param name="delay">调用延迟</param>
    /// <param name="doTimes">调用次数，-1表示无限循环</param>
    /// <param name="repeatInterva">调用间隔</param>
    /// <returns>Timer Id</returns>
    public int StartTimer(CancellationToken cancellationToken, Action callBack, float delay = 0f, int doTimes = 1,
        float repeatInterva = 1f)
    {
        int timerId = timerIdGenerator.Next;
        var coroutine =
            Global.CoroutineMgrIns.StartCoroutine(TimeCoroutine(timerId, callBack, delay, doTimes, repeatInterva),
                cancellationToken);
        timerCoroutines.Add(timerId, coroutine);
        return timerId;
    }

    /// <summary>
    /// 手动结束计时器
    /// </summary>
    /// <param name="timerId"></param>
    public void EndTimer(int timerId)
    {
        if (timerCoroutines.TryGetValue(timerId, out var coroutine))
        {
            Global.CoroutineMgrIns.StopCoroutine(coroutine);
            timerCoroutines.Remove(timerId);
        }
    }

    private IEnumerator TimeCoroutine(int timerId, Action callBack, float delay = 0f, int doTimes = 1,
        float repeatInterval = 1f)
    {
        float timeTick = repeatInterval;
        int finishCount = 0;
        bool isLoop = doTimes == -1;
        yield return new WaitForSeconds(delay);

        if (isLoop)
        {
            while (true)
            {
                if (timeTick >= repeatInterval)
                {
                    callBack?.Invoke();
                    timeTick = 0f;
                }

                timeTick += Time.deltaTime;
                yield return null;
            }
        }
        else
        {
            while (finishCount < doTimes)
            {
                if (timeTick >= repeatInterval)
                {
                    callBack?.Invoke();
                    timeTick = 0f;
                    finishCount++;
                }

                timeTick += Time.deltaTime;
                yield return null;
            }
        }

        EndTimer(timerId);
    }
}